<template>
  <div id="EquipmentDetailsPage">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">设备详情</span>
      </div>
      <div class="content-wrapper">
        <div class="back-btn" @click="backHandle">返回</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="equipment-detail" v-if="equipmentInfo">
        <div class="left-content">
          <div class="equipment-image">
            <img
              :src="
                equipmentInfo.photoList[0]?.url ||
                require('@/assets/images/defaultDevice.png')
              "
              alt="设备图片"
              class="equipment-photo"
            />
          </div>
        </div>
        <div class="right-content">
          <div class="header-row">
            <div class="title-section">
              <span class="equipment-name">{{ equipmentInfo.name }}</span>
              <el-button size="small" class="type-btn">{{
                equipmentInfo.typeInfo?.name
              }}</el-button>
              <div class="status-tag" :class="equipmentInfo.status">
                {{ statusMap[equipmentInfo.status] }}
              </div>
            </div>
            <div class="action-btn">
              <el-button
                type="primary"
                size="small"
                @click="editHandle(equipmentInfo)"
                >编辑</el-button
              >
            </div>
          </div>

          <div class="sn-model-row">
            <span class="label">序列号: {{ equipmentInfo.code }}</span>
            <span class="separator">|</span>
            <span class="label">型号: {{ equipmentInfo.model }}</span>
          </div>

          <div class="info-table">
            <div class="info-row">
              <div class="info-item">
                <span class="label">采购时间</span>
                <span class="value">{{
                  formatDate(equipmentInfo.purchaseDate || 0)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">投运时间</span>
                <span class="value">{{
                  formatDate(equipmentInfo.deliveryDate || 0)
                }}</span>
              </div>
              <div class="info-item">
                <span class="label">使用年限</span>
                <span class="value">{{ equipmentInfo.useYears }}年</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">所属院系</span>
                <span class="value">{{ ogaMap[equipmentInfo.belong] }}</span>
              </div>
              <div class="info-item">
                <span class="label">当前位置</span>
                <span class="value">{{ equipmentInfo.location }}</span>
              </div>
              <div class="info-item">
                <span class="label">当前责任人</span>
                <span class="value">{{
                  equipmentInfo.chargeUserInfo?.name || "--"
                }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">设备价值</span>
                <span class="value">{{
                  formatCurrency(equipmentInfo.purchasePrice || 0)
                }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">备注1</span>
                <span class="value">{{
                  equipmentInfo.description1 || "--"
                }}</span>
              </div>
            </div>

            <div class="info-row">
              <div class="info-item">
                <span class="label">备注2</span>
                <span class="value">{{
                  equipmentInfo.description2 || "--"
                }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div v-else class="loading-wrapper">
        <div>加载中...</div>
      </div>

      <!-- 设备图片管理 -->
      <div class="equipment-attachment-wrapper">
        <EquipmentAttachment :equipmentId="equipmentId" />
      </div>
      <!-- 设备文档管理 -->

      <div class="maintenance-plan-wrapper">
        <MaintenancePlan />
      </div>
      <div class="repair-work-order-wrapper">
        <RepairWorkOrder :userList="userList" />
      </div>
      <div class="other-info-wrapper">
        <div class="contact-wrapper">
          <Contact />
        </div>
        <div class="contract-wrapper">
          <Contract />
        </div>
      </div>
    </div>

    <!-- 编辑设备弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="editDialogVisible"
      title="编辑设备"
      width="50%"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="设备名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入设备名称"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="设备类型" prop="typeId">
          <el-select v-model="editForm.typeId" placeholder="请选择设备类型">
            <el-option
              v-for="item in equipmentTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="序列号" prop="code">
          <el-input
            v-model="editForm.code"
            placeholder="请输入设备序列号"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="型号" prop="model">
          <el-input v-model="editForm.model" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="负责人" prop="responsiblePerson">
          <el-select
            v-model="editForm.chargeUserCode"
            placeholder="请选择负责人"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item.userCode"
              filterable
            />
          </el-select>
        </el-form-item>
        <el-form-item label="设备状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择设备状态">
            <el-option label="空闲中" :value="'IDLE'" />
            <!-- <el-option label="预约中" :value="'RESERVEING'" /> -->
            <el-option label="使用中" :value="'IN_USE'" />
            <!-- <el-option label="维护中" :value="'REPAIRING'" /> -->
            <el-option label="损坏" :value="'DAMAGED'" />
            <el-option label="报废" :value="'SCRAPPED'" />
          </el-select>
        </el-form-item>
        <el-form-item label="设备位置" prop="location">
          <el-input
            v-model="editForm.location"
            placeholder="请输入设备位置"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="设备归属" prop="belong">
          <el-select v-model="editForm.belong" placeholder="请选择设备归属">
            <el-option
              v-for="item in ogaList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采购时间" prop="procurementTime">
          <el-date-picker
            v-model="editForm.purchaseDate"
            type="date"
            format="YYYY/MM/DD"
            value-format="x"
            placeholder="请选择采购时间"
            style="width: 100%"
            :disabledDate="disableFutureDates"
          />
        </el-form-item>
        <el-form-item label="投运时间" prop="operationalTime">
          <el-date-picker
            v-model="editForm.deliveryDate"
            type="date"
            format="YYYY/MM/DD"
            value-format="x"
            placeholder="请选择投运时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="采购价格" prop="purchasePrice">
          <el-input
            v-model="editForm.purchasePrice"
            placeholder="请输入设备价值（元）"
            style="width: 80%"
          />（元）
        </el-form-item>
        <el-form-item label="使用年限" prop="useYears">
          <el-input-number
            v-model="editForm.useYears"
            :min="1"
            :max="100"
            :step="1"
            placeholder="请输入设备使用年限（年）"
            style="width: 80%"
            controls-position="right"
          />（年）
        </el-form-item>
        <el-form-item label="备注1" prop="note1">
          <el-input
            v-model="editForm.description1"
            placeholder="请输入设备备注1"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注2" prop="note2">
          <el-input
            v-model="editForm.description2"
            placeholder="请输入设备备注2"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitEditForm"
            :loading="editFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import Contact from "@/components/Contact.vue";
import Contract from "@/components/Contract.vue";
import MaintenancePlan from "@/components/MaintenancePlan.vue";
import RepairWorkOrder from "@/components/RepairWorkOrder.vue";
import EquipmentAttachment from "@/components/EquipmentAttachment.vue";
import {
  getEquipmentByIdAPI,
  addOrUpdateEquipmentAPI,
  typesAPI,
} from "@/api/service/equipmentManage";
import {
  EquipmentType,
  AddOrUpdateEquipmentQueryType,
  EquipmentStatus,
} from "@/api/types/equipment";
import { getOgaListAPI, OgaType } from "@/api/service/oga";
import { getUserListAPI, UserType, GetUserListType } from "@/api/service/user";
import { formatCurrency, formatDate } from "@/assets/js/utils";

const route = useRoute();
const router = useRouter();
const equipmentId = route.query.id as string;

// 获取用户列表
const userList = ref<UserType[]>([]);
const userListLoading = ref(false);
const userListQuery = ref<GetUserListType>({
  page: 1,
  size: 1000,
  name: "",
  ogaCode: "",
});
function getUserList() {
  if (userListLoading.value) return;
  userListLoading.value = true;
  getUserListAPI({
    name: userListQuery.value.name,
    ogaCode: userListQuery.value.ogaCode,
    page: userListQuery.value.page,
    size: userListQuery.value.size,
  })
    .then((res: any) => {
      userList.value = res.content;
    })
    .finally(() => {
      userListLoading.value = false;
    });
}
getUserList();

// 获取设备类型列表
const equipmentTypeList = ref<EquipmentType[]>([]);
const equipmentTypeListLoading = ref(false);
function getEquipmentTypeList() {
  if (equipmentTypeListLoading.value) return;
  equipmentTypeListLoading.value = true;
  typesAPI()
    .then((res: any) => {
      equipmentTypeList.value = res.deviceTypes || [];
    })
    .catch(() => {
      ElMessage.error("获取设备类型列表失败");
    })
    .finally(() => {
      equipmentTypeListLoading.value = false;
    });
}
getEquipmentTypeList();

// 获取组织结构列表
const ogaList = ref<OgaType[]>([]);
const ogaMap = ref<Record<string, string>>({});
const ogaListApiLoading = ref(false);

// 加载组织列表
const loadOgaList = async () => {
  try {
    if (ogaListApiLoading.value) return;
    ogaListApiLoading.value = true;

    const response = await getOgaListAPI();
    const result = response as any as OgaType[];
    if (result) {
      ogaList.value = result || [];
      ogaList.value?.forEach((item) => {
        ogaMap.value[item.code] = item.name;
      });
    }
  } catch (error) {
    ElMessage.error("获取组织列表失败");
    console.error("Load oga list error:", error);
  } finally {
    ogaListApiLoading.value = false;
  }
};
loadOgaList();

// 设备基本信息
const statusMap = ref<Record<string, string>>({
  IDLE: "空闲中",
  // RESERVEING: "预约中",
  IN_USE: "使用中",
  // REPAIRING: "维护中",
  DAMAGED: "损坏",
  SCRAPPED: "报废",
});
const equipmentInfo = ref<any>();

// API调用保护状态
const equipmentInfoApiLoading = ref(false);

function getEquipmentInfo() {
  // 防止并发调用
  if (equipmentInfoApiLoading.value) return;

  equipmentInfoApiLoading.value = true;

  getEquipmentByIdAPI(equipmentId)
    .then((_data: any) => {
      const data = _data as EquipmentType;
      equipmentInfo.value = data;
    })
    .catch(() => {
      ElMessage.error("获取设备详情失败");
    })
    .finally(() => {
      equipmentInfoApiLoading.value = false;
    });
}
getEquipmentInfo();

// 编辑设备基本信息
const editDialogVisible = ref(false);
const editFormRef = ref();
const editFormLoading = ref(false);
const editForm = ref<AddOrUpdateEquipmentQueryType>({
  id: "",
  name: "",
  typeId: "",
  code: "",
  model: "",
  chargeUserCode: "",
  status: EquipmentStatus.IDLE,
  location: "",
  belong: "",
  purchaseDate: 0,
  deliveryDate: 0,
  useYears: 0,
  purchasePrice: 0,
  description1: "",
  description2: "",
});

// 编辑设备
function editHandle(row: any) {
  editDialogVisible.value = true;
  editForm.value = {
    id: row.id,
    name: row.name,
    typeId: row.typeInfo?.id,
    code: row.code,
    model: row.model,
    chargeUserCode: row.chargeUserCode,
    status: row.status,
    location: row.location,
    belong: row.belong,
    purchaseDate: row.purchaseDate,
    deliveryDate: row.deliveryDate,
    useYears: row.useYears,
    purchasePrice: row.purchasePrice,
    description1: row.description1,
    description2: row.description2,
  };
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    editFormRef.value?.clearValidate();
  });
}

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const editFormRules = {
  name: [{ required: true, message: "请输入设备名称", trigger: "blur" }],
  typeId: [{ required: true, message: "请选择设备类型", trigger: "blur" }],
  code: [{ required: true, message: "请输入设备序列号", trigger: "blur" }],
};

// 重置添加表单
function resetEditForm() {
  editForm.value = {
    id: "",
    name: "",
    typeId: "",
    code: "",
    model: "",
    chargeUserCode: "",
    status: EquipmentStatus.IDLE,
    location: "",
    belong: "",
    purchaseDate: 0,
    deliveryDate: 0,
    useYears: 0,
    purchasePrice: 0,
    description1: "",
    description2: "",
  };
  editFormRef.value?.clearValidate();
}

// 日期验证函数 - 禁用今日之后的日期
const disableFutureDates = (time: Date) => {
  const today = new Date();
  today.setHours(23, 59, 59, 999); // 设置为今日的最后一刻
  return time.getTime() > today.getTime();
};

// 提交添加表单
function submitEditForm() {
  // 防止并发提交
  if (editFormLoading.value) return;

  editFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      editFormLoading.value = true;
      addOrUpdateEquipmentAPI({
        id: editForm.value.id,
        name: editForm.value.name,
        typeId: editForm.value.typeId,
        code: editForm.value.code,
        model: editForm.value.model,
        chargeUserCode: editForm.value.chargeUserCode,
        status: editForm.value.status,
        location: editForm.value.location,
        belong: editForm.value.belong,
        purchaseDate: editForm.value.purchaseDate,
        deliveryDate: editForm.value.deliveryDate,
        useYears: editForm.value.useYears,
        purchasePrice: editForm.value.purchasePrice,
        description1: editForm.value.description1,
        description2: editForm.value.description2,
      })
        .then(() => {
          ElMessage.success(
            editForm.value.id ? "编辑设备成功" : "添加设备成功"
          );
          editDialogVisible.value = false;
          resetEditForm();
          // 刷新列表
          getEquipmentInfo();
        })
        .catch(() => {
          ElMessage.error(editForm.value.id ? "编辑设备失败" : "添加设备失败");
        })
        .finally(() => {
          editFormLoading.value = false;
        });
    }
  });
}
// 返回
function backHandle() {
  router.back();
}
</script>

<style scoped lang="scss">
#EquipmentDetailsPage {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
  padding: 1.5rem;
  background-color: #fff;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
  }
  .back-btn {
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 2rem;
  overflow: auto;

  .equipment-detail {
    display: flex;
    gap: 2rem;
    border-radius: 8px;
    padding: 2rem 2rem 1rem 2rem;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  }

  .left-content {
    width: 300px;
    .equipment-image {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: center;

      img {
        max-width: 100%;
        max-height: 100%;
        object-fit: contain;
      }
    }
  }

  .right-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 1rem;
    margin-left: 1rem;
    .header-row {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;

      .title-section {
        display: flex;
        align-items: center;
        gap: 1rem;

        .equipment-name {
          font-size: $font-size-block-title;
          font-weight: 500;
          color: #fff;
          font-family: "Alibaba-PuHuiTi-Medium";
        }

        .type-btn {
          background-color: #ba7bfb;
          color: #fff;
          border-radius: 1rem;
          border: none;
        }

        .status-tag {
          padding: 0.25rem 1rem;
          border-radius: 1rem;
          font-size: $font-size-tips;
          font-weight: 500;

          &.IDLE {
            background-color: #fff;
            color: $text-color-regular;
          }
          &.RESERVEING {
            background-color: $color_warning;
            color: $text-color-regular;
          }

          &.DAMAGED {
            background-color: $color_danger;
            color: $text-color-regular;
          }
          &.IN_USE {
            background-color: $color_success;
            color: $text-color-regular;
          }
          &.REPAIRING {
            background-color: $color_warning;
            color: $text-color-regular;
          }
          &.SCRAPPED {
            background-color: $color_danger;
            color: $text-color-regular;
          }
        }
      }
    }

    .sn-model-row {
      font-size: $font-size-tips;
      color: $text-color-regular;
      margin-bottom: 1rem;

      .separator {
        color: $text-color-regular;
        margin: 0 0.5rem;
      }
    }

    .info-table {
      display: flex;
      flex-direction: column;
      gap: 0.5rem;

      .info-row {
        display: grid;
        grid-template-columns: 1fr 1fr 1fr;
        margin-bottom: 1rem;
      }

      .info-item {
        display: flex;
        align-items: center;
        min-width: 180px;

        .label {
          display: inline-block;
          width: 80px;
          color: $text-color-regular;
          font-size: $font-size-base;
          text-align: left;
          flex-shrink: 0;
        }

        .value {
          color: $text-color-regular;
          font-size: $font-size-tips;
          margin-left: 0.5rem;
        }
      }
    }
  }

  .loading-wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    color: $text-color-secondary;
    font-size: $font-size-base;
  }

  .equipment-attachment-wrapper {
    margin-top: 2rem;
    border: 1px solid $border-color-primary;
    border-radius: 8px;
    padding: 0 0 2rem 0;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    // background-color: $text-color-placeholder;
  }
  .maintenance-plan-wrapper {
    margin-top: 2rem;
    border: 1px solid $border-color-primary;
    border-radius: 8px;
    padding: 0 0 2rem 0;
    background-color: #fff;
    // background-color: $text-color-placeholder;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
  .repair-work-order-wrapper {
    margin-top: 2rem;
    border: 1px solid $border-color-primary;
    border-radius: 8px;
    padding: 0 0 2rem 0;
    background-color: #fff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    // background-color: $text-color-placeholder;
  }
  .other-info-wrapper {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 3rem;
    margin-top: 2rem;
    .contact-wrapper {
      border: 1px solid $border-color-primary;
      border-radius: 8px;
      padding: 0 0 2rem 0;
      background-color: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      // background-color: $text-color-placeholder;
    }
    .contract-wrapper {
      border: 1px solid $border-color-primary;
      border-radius: 8px;
      padding: 0 0 2rem 0;
      background-color: #fff;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      // background-color: $text-color-placeholder;
    }
  }
}

:deep(.el-input__inner) {
  text-align: left !important;
}
</style>
